#coding:utf-8
from django_jinja import library
import re


lib = library.Library()


@lib.filter
def cut_str(origin_str, length=10):
    #截取字符串，使得字符串长度等于length，并在字符串后加上省略号
    origin_str = re.compile(r'<[^>]+>\s*', re.S).sub('', origin_str)
    origin_str = re.compile(r'^(&nbsp;|\s|\t)*', re.S).sub('', origin_str)

    try:
        str_encode = origin_str.encode('gb18030')  # 为了中文和英文的长度一致（中文按长度2计算）

        l = length * 2
        if l < len(str_encode):
            l -= 3
            str_encode = str_encode[:l]
            try:
                origin_str = str_encode.decode('gb18030') + '...'
            except StandardError, api_error:
                str_encode = str_encode[:-1]
                try:
                    origin_str = str_encode.decode('gb18030') + '...'
                except StandardError, api_error:
                    if length < len(origin_str):
                        length -= 2
                        return origin_str[:length] + '...'
    except StandardError, api_error:
        if length < len(origin_str):
            length -= 2
            return origin_str[:length] + '...'

    return origin_str